﻿using System.Security.Principal;
using System.Threading;
using System.Web;
using System.Web.Security;
using RuTracker.Interface;
using RuTrackerLib;

namespace RuTracker.MVC.Core.CustomAuth
{
    public static class AuthenticationRequestHandler
    {
        public static void Handle(HttpContext context, HttpRequest request)
        {
            IUserRepository repository = Container.Current.Resolve<IUserRepository>();
            HttpCookie cookie = request.Cookies[FormsAuthentication.FormsCookieName];
            string userName = DecodeUserNameFromCookie(cookie);

            if (!string.IsNullOrEmpty(userName))
            {
                IIdentity identity = repository.GetUser(userName) != null
                                         ? new GenericIdentity(userName)
                                         : null;

                IPrincipal principal = identity != null
                                           ? new GenericPrincipal(identity, new string[0])
                                           : null;


                Thread.CurrentPrincipal = context.User = principal;
            }
        }

        private static string DecodeUserNameFromCookie(HttpCookie cookie)
        {
            if (cookie == null)
                return string.Empty;
            
            
            string result = string.Empty;

            try
            {
                var authTicket = FormsAuthentication.Decrypt(cookie.Value);
                result = authTicket.Name;
            }
            catch
            {
                Log.Error("Cannot decode authorization cookie");
            }

            return result;
        }
    }
}